﻿using System.Reflection;
using System.Text.Json.Nodes;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Abstractions;
using Microsoft.AspNetCore.Mvc.Controllers;
using Microsoft.AspNetCore.Mvc.Filters;
using Zero.WebAPI.Framework.Attr;
using Zero.WebAPI.Framework.Security;
using Zero.WebAPI.Framework.Security.Model;

namespace Zero.WebAPI.Framework.Filter
{
    /// <summary>
    /// 权限拦截器
    /// </summary>
    public class PermissionInterceptor : IActionFilter
    {
        private IPermissionService permissionService;

        public PermissionInterceptor(IPermissionService permissionService)
        {
            this.permissionService = permissionService;
        }

        public void OnActionExecuting(ActionExecutingContext context)
        {
            ActionDescriptor actionDescriptor = context.ActionDescriptor;
            if (!(actionDescriptor is ControllerActionDescriptor))
                return;
            ControllerActionDescriptor? descriptor = actionDescriptor as ControllerActionDescriptor;

            // 获取方法上的 PermissionAttribute
            var methodPerms = descriptor.MethodInfo.GetCustomAttribute<PermissionAttribute>();
            // 获取控制器类上的 PermissionAttribute
            var classPerms = descriptor.ControllerTypeInfo.GetCustomAttribute<PermissionAttribute>();

            // 示例逻辑：方法优先级高于类
            var effectivePerms = methodPerms ?? classPerms;

            if (effectivePerms != null)
            {
                List<string> needPerms = effectivePerms.Perms.Split(",").ToList();
                Identity? user = context.HttpContext.Items["user"] as Identity;
                if (user == null)
                {
                    context.Result = new JsonResult(new
                    {
                        code = 403,
                        message = "权限不足，拒绝访问"
                    })
                    { StatusCode = 403 };
                    
                }
                bool flag = permissionService.CheckPermission(user, needPerms);
                if (flag)
                    return;
                context.Result = new JsonResult(new {code = 403,message = "权限不足，拒绝访问" }) { StatusCode = 403};
            }
        }


        public void OnActionExecuted(ActionExecutedContext context)
        {

        }
    }
}
